import _ from 'lodash'
import React, { Component } from 'react'
import Search from 'antd/lib/input/Search'
import { Tree, Icon, Tooltip, Modal, message } from 'antd'
import { AntTreeNodeSelectedEvent } from 'antd/lib/tree'
import { uaaApp, http } from '@/lib'
import { findTreeNodeInfo } from '@/utils/methods'
import { ESystemMenuType } from '@/utils/types'
import apis from '@/apis/MenusManage'
import NotFoundContent from '@/components/NotFoundContent'

const { TreeNode } = Tree

class MenuTree extends Component<IMenuTreeProps, IMenuTreeState> {

  private mapping: any = {}

  constructor(props: IMenuTreeProps) {
    super(props)
    this.state = {
      nodes: [],
      oldNodes: [],
      keyword: '',
      selectedNodeKeys: [],
      expandedKeys: [],
      autoExpandParent: false,
    }
  }

  componentDidMount() {
    // let nodes = this.transformItemsData(this.props.items)
    let nodes = this.props.items
    this.setState({ nodes, oldNodes: nodes })
  }

  componentWillReceiveProps(nextProps: IMenuTreeProps) {
    // console.log('改变11', nextProps.items)
    if (!_.isEqual(this.props.items, nextProps.items)) {
      // let nodes = this.transformItemsData(nextProps.items)
      let nodes = nextProps.items
      this.setState({ nodes, oldNodes: nodes })
    }
  }

  render() {
    return (
      <div className="menu-tree">
        <div className="box-title">菜单列表</div>
        <Search placeholder="搜索" onSearch={this.onSearch} />
        <div className="toolbar">
          <a onClick={() => {
            this.setState({ selectedNodeKeys: [] })
            this.props.onSelect('add', null)
          }}><Icon type="plus" />添加一级菜单</a>
        </div>
        {(this.state.nodes && this.state.nodes.length) ? <Tree
          onExpand={this.onExpand}
          expandedKeys={this.state.expandedKeys}
          selectedKeys={this.state.selectedNodeKeys}
          autoExpandParent={this.state.autoExpandParent}
          onSelect={this.selectNode}
        >
          {this.renderTreeNode(this.state.nodes)}
        </Tree> : <div style={{marginTop: 40}}><NotFoundContent desc='未找到相关菜单' /></div> }
      </div>
    )
  }

  private transformItemsData = (items: any[]) => {
    console.log(items)
    this.mapping = {}
    if (items == null || items.length == 0) {
      return []
    }
    items = _.cloneDeep(items)

    let itemParentsId = ''
    let resourceParentsId = ''
    let recursion = (data: any[]) => {
      if (data && data.length > 0) {
        data.forEach(n => {
          n.key = n.id + '|' + n.type

          if (n.type === 'MENU_ITEM') {
            n.parent = itemParentsId
          }
          if (n.type === 'RESOURCE') {
            n.parent = resourceParentsId
            n.grandParent = itemParentsId
          }

          this.mapping[n.key] = n

          if (n.items && n.items.length > 0) {

            if (n.type === 'MENU_GROUP') {
              itemParentsId = n.key
            }

            if (n.type === 'MENU_ITEM') {
              resourceParentsId = n.key
            }

            recursion(n.items)
          }
        })
      }
    }
    recursion(items)
    return items
  }

  private renderTreeNode = (nodes: any[]) => {
    return nodes.map(node => {
      let hasChildren = node.children && node.children.length > 0
      // let canDel = uaaApp.canUse('_uaa_authority_authorization_list_delete')
      let canDel = true
      // let canAdd = uaaApp.canUse('_uaa_authority_authorization_list_add')
      let canAdd = node.type !== ESystemMenuType.RESOURCE ? true : false
      let index = node.title.indexOf(this.state.keyword)
      const beforeStr = node.title.substr(0, index);
      const afterStr = node.title.substr(index + this.state.keyword.length);
      let title = <>
        <span className="title">{index > -1 ? <span>{beforeStr}<span style={{ color: '#f50' }}>{this.state.keyword}</span>{afterStr}</span> : <span>{node.title}</span>}</span>
        <span className="links">
          {
            canAdd && <Tooltip title="添加子级菜单">
              <Icon onClick={e => {
                e.stopPropagation()
                this.props.onSelect('add', node)
              }} type="plus" />
            </Tooltip>
          }
          {
            canDel && <Tooltip title="删除该菜单">
              <Icon onClick={e => {
                e.stopPropagation()
                this.removeTree(node)
              }} type="delete" />
            </Tooltip>
          }
        </span>
      </>
      return <TreeNode key={node.key} title={title}>
        {hasChildren ? this.renderTreeNode(node.children) : null}
      </TreeNode>
    })
  }

  protected onSearch = (value) => {
    const expandedKeys = this.getParentKey(value, this.state.oldNodes)
    this.setState({ keyword: value, expandedKeys })
  }

  // 
  private getParentKey = (keywords, tree) => {
    let parentKey: any = [];
    let newTree: any = []
    if (keywords === '') {
      this.setState({
        nodes: this.state.oldNodes
      })
      return parentKey
    }

    const getGroup = (key) => {
      tree.forEach((item: any) => {
        if (item.key === key) {
          newTree.push(item)
        }
      });
    }

    const recursive = (arr) => {
      arr.forEach((v: any) => {
        if (v.items && v.items.length > 0) {
          recursive(v.items)
        }
        if (v.type === ESystemMenuType['MENU_GROUP'] && v.title.indexOf(keywords) > -1) {
          if (parentKey.indexOf(v.parent) <= -1) {
            parentKey.push(v.parent)
            getGroup(v.key)
          }
        }
        if (v.type === ESystemMenuType['MENU_ITEM'] && v.title.indexOf(keywords) > -1) {
          if (parentKey.indexOf(v.parent) <= -1) {
            parentKey.push(v.parent)
            getGroup(v.key)
          }
        }
        if (v.type === ESystemMenuType['RESOURCE'] && v.title.indexOf(keywords) > -1) {
          if (parentKey.indexOf(v.parent) <= -1) {
            parentKey.push(v.parent)
            getGroup(v.parent)
          }
          if (parentKey.indexOf(v.grandParent) <= -1) {
            parentKey.push(v.grandParent)
            getGroup(v.grandParent)
          }
        }
      });
    }
    recursive(tree)

    newTree = _.uniqBy(newTree, 'key')
    if (newTree.length > 0) {
      this.setState({
        nodes: newTree
      })
    } else {
      this.setState({
        nodes: []
      })
    }

    return parentKey
  }

  private selectNode = (selectedKeys: string[], e: AntTreeNodeSelectedEvent) => {
    let key = ''
    if (e.selected) {
      this.setState({ selectedNodeKeys: selectedKeys })
      key = selectedKeys[0]
    } else {
      key = this.state.selectedNodeKeys[0]
    }
    const nodeInfo = findTreeNodeInfo(this.state.nodes,key,'key')
    if (nodeInfo) {
      this.props.onSelect('edit', nodeInfo)
    }
  }

  protected onExpand = expandedKeys => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  }

  // 删除菜单
  protected removeTree = (node: any) => {
    const _this = this
    Modal.confirm({
      title: '菜单将被删除，请确认是否删除？',
      onOk() {
        const params = {
          id: node.id,
        }
        http.delete(apis.DeleteMenu, {params}).then(res => {
          message.success('删除成功');
          _this.props.submitSuccess()
          _this.props.onSelect('delete', null)
        })
      },
    })
  }
}

interface IMenuTreeProps {
  items: any[]
  submitSuccess?: any
  onSelect: (type: any, item: any) => void
}

interface IMenuTreeState {
  nodes: any[]
  keyword: string
  expandedKeys: any[]
  selectedNodeKeys: string[],
  autoExpandParent: boolean,
  oldNodes: any[]
}

export default MenuTree
